#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:3年内申请企业历史失信情况
code:EG_DishonestyInThree
tableName:
columnName:
groups:准入>企业业务信息校验
dependencies:EG_CASE_DSJ
type:常用指标
dataSourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import datetime
import re

reload(sys)
sys.setdefaultencoding('utf-8')

last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y-%m-%d') \
                  for i in [3, 0]]

null_type_list = ['', None, 'null', 'Null', 'NULL', '/', ' ']


def FormatData(tableName):
    try:
        eg = EG_CASE_DSJ.get("data").get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


def Ent_Dishonesty_3Yr():
    dishonestyList = FormatData("R230")
    if dishonestyList == [{}]:
        return u'缺失值'
    else:
        if len(dishonestyList) >= 1:
            duplicate_list = []
            resultList = []
            flag = False
            for i in dishonestyList:
                REGDATE = i.get("REGDATE")
                try:
                    REGDATE = Formate(REGDATE[:10])
                except:
                    REGDATE = None
                CASECODE = i.get("CASECODE")
                if REGDATE not in null_type_list and CASECODE not in null_type_list and \
                        CASECODE not in duplicate_list:
                    duplicate_list.append(CASECODE)
                    flag = True
                    if last_year_list[0] < REGDATE < last_year_list[1]:
                        resultList.append(1)
            return len(resultList) if flag else u'缺失值'
        else:
            return 0


def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date


if __name__ == '__main__':
    import json

    file_obj = open(r'../../data/EG_DishonestyInThree/EG_CASE_DSJ.json', 'r')
    content = file_obj.read()
    EG_CASE_DSJ = json.loads(content, strict=False)
    aa = Ent_Dishonesty_3Yr()
    print aa

result = Ent_Dishonesty_3Yr()
